package com.spelet.simulation;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.spelet.StaticFonts;

public class SaveMapFile {
	Sprite bgborder;
	String name;
	int timer;
	Array<ErrorMessage> errors;
	int activeErrorMessages;
	public SaveMapFile()  {
		errors = new Array<ErrorMessage>();
		activeErrorMessages = 0;
		name = "";
		bgborder = new Sprite(new Texture(Gdx.files.internal("data/LoadFileMap/border.png")));
		bgborder.setX(Gdx.graphics.getWidth()*0.88f/2-bgborder.getWidth()/2);
		bgborder.setY(Gdx.graphics.getHeight()/2-bgborder.getHeight()/2*0.47f);
	}
	public boolean hit(int x, int y) {
		return bgborder.getBoundingRectangle().contains(x,y);
	}
	public void pressed(int x, int y) {
		
	}
	public void render(OrthographicCamera cam, SpriteBatch sb) {
		bgborder.draw(sb);
		String dots = "";
		timer += Gdx.graphics.getDeltaTime()*1000;
		if (timer < 400)
			dots = ".";
		else if (timer < 800)
			dots = "..";
		else if (timer < 1200)
			dots = "..."; 
		else {
			dots = ".";
			timer = 0;
		}
		StaticFonts.basicFont.drawMultiLine(sb, "Saving file.\nCurrent file name is: " + name + dots,bgborder.getX()+bgborder.getWidth()/10,bgborder.getY()+bgborder.getHeight()*0.9f);
		
		int errorsDisplayed = 0;
		int active=0;
		String errmsg="";
		for (int i = errors.size-1; i >= 0; i--) {
			if (TimeUtils.millis()-errors.get(i).time < 2000) {
				if (errorsDisplayed < 5) {
					active++;
					errorsDisplayed++;
					errmsg = errmsg + errors.get(i).error+"\n";	
				}
			}
		}
		activeErrorMessages = active;
		StaticFonts.basicFont.drawMultiLine(sb, errmsg,bgborder.getX()+bgborder.getWidth()/10,bgborder.getY()+StaticFonts.basicFont.getLineHeight()*5);
	}
	public void setName(String name) {
		this.name= name;
	}
	public void addErrorMessage(String msg) {
		System.out.println("AE " + activeErrorMessages + "ES" + errors.size);
		if (activeErrorMessages == errors.size) {
			errors.add(new ErrorMessage(msg,TimeUtils.millis()));
			activeErrorMessages++;
		} else if (activeErrorMessages < errors.size) {
			for (int i = 0; i < errors.size; i++) {
				if (TimeUtils.millis()-errors.get(i).time > 2000) {
					ErrorMessage e = errors.get(i);
					errors.removeIndex(i);
					e.error = msg;
					e.time = TimeUtils.millis();
					errors.add(e);
					activeErrorMessages++;
					break;
				}
			}
		}
	}

}
